import React, { useEffect, useState } from "react";
import { Card, Table, Form, Input, Button, Space, Select, DatePicker, message } from "antd";
import type { ColumnsType } from "antd/es/table";
import { request } from "../../../utils/request";
import moment from "moment";

const { RangePicker } = DatePicker;
const { Option } = Select;

interface Subscriber {
  id: number;
  user_uuid: string;
  email: string;
  ai_person_id: number;
  ai_person_name: string;
  status: string;
  auto_renew: boolean;
  cancel_at_period_end: boolean;
  tokens_per_cycle: string;
  current_period_start: string | null;
  current_period_end: string | null;
  next_renew_at: string | null;
  last_renewed_at: string | null;
  canceled_at: string | null;
  metadata: any;
  created_at: string | null;
  updated_at: string | null;
}

const AgentSubscription: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<Subscriber[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    fetchList();
  }, [page, pageSize]);

  const buildParams = (values: any) => {
    const params: any = { page, pageSize };
    if (values.email) params.email = values.email;
    if (values.ai_person_id) params.ai_person_id = values.ai_person_id;
    if (values.status) params.status = values.status;
    if (values.updated_at_range && values.updated_at_range.length === 2) {
      params.updated_at_from = values.updated_at_range[0].startOf("day").toISOString();
      params.updated_at_to = values.updated_at_range[1].endOf("day").toISOString();
    }
    return params;
  };

  const fetchList = async (vals?: any) => {
    setLoading(true);
    try {
      const values = vals || form.getFieldsValue();
      const params = buildParams(values);
      const res = await request.post("/api/admin/agent/subscribers", params);
      if (res && res.data && res.data.success) {
        const d = res.data.data;
        setData(d.subscribers || []);
        setTotal(d.total || 0);
        setPage(d.page || page);
        setPageSize(d.pageSize || pageSize);
      } else {
        message.error("获取订阅列表失败");
      }
    } catch (e) {
      console.error(e);
      message.error("获取订阅列表异常");
    } finally {
      setLoading(false);
    }
  };

  const onSearch = () => {
    setPage(1);
    fetchList();
  };

  const onReset = () => {
    form.resetFields();
    setPage(1);
    fetchList({});
  };

  const columns: ColumnsType<Subscriber> = [
    { title: "ID", dataIndex: "id", key: "id", width: 80 },
    { title: "用户UUID", dataIndex: "user_uuid", key: "user_uuid" },
    { title: "邮箱", dataIndex: "email", key: "email" },
    { title: "AI人物ID", dataIndex: "ai_person_id", key: "ai_person_id" },
    { title: "AI人物名称", dataIndex: "ai_person_name", key: "ai_person_name" },
    { 
      title: "状态", 
      dataIndex: "status", 
      key: "status",
      render: (s: string) => {
        const map: Record<string, string> = {
          active: "激活",
          canceled: "已取消",
          expired: "已过期",
          suspended: "已暂停",
        };
        return map[s] || s;
      }
    },
    { title: "是否自动续费", dataIndex: "auto_renew", key: "auto_renew", render: (v: boolean) => (v ? "是" : "否") },
    { title: "当前周期开始", dataIndex: "current_period_start", key: "current_period_start", render: (t: string) => (t ? new Date(t).toLocaleString() : "-") },
    { title: "当前周期结束", dataIndex: "current_period_end", key: "current_period_end", render: (t: string) => (t ? new Date(t).toLocaleString() : "-") },
    { title: "下次续费时间", dataIndex: "next_renew_at", key: "next_renew_at", render: (t: string) => (t ? new Date(t).toLocaleString() : "-") },
    { title: "最后续费时间", dataIndex: "last_renewed_at", key: "last_renewed_at", render: (t: string) => (t ? new Date(t).toLocaleString() : "-") },
    { title: "创建时间", dataIndex: "created_at", key: "created_at", render: (t: string) => (t ? new Date(t).toLocaleString() : "-") },
    { title: "更新时间", dataIndex: "updated_at", key: "updated_at", render: (t: string) => (t ? new Date(t).toLocaleString() : "-") },
  ];

  return (
    <Card>
      <Form form={form} layout="inline" style={{ marginBottom: 12 }}>
        <Form.Item name="email">
          <Input placeholder="邮箱" />
        </Form.Item>
        <Form.Item name="ai_person_id">
          <Input placeholder="AI人物ID" />
        </Form.Item>
        <Form.Item name="status">
          <Select style={{ width: 140 }} placeholder="状态">
            <Option value="">全部</Option>
            <Option value="active">active</Option>
            <Option value="canceled">canceled</Option>
            <Option value="expired">expired</Option>
            <Option value="suspended">suspended</Option>
          </Select>
        </Form.Item>
        <Form.Item name="updated_at_range">
          <RangePicker />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={onSearch}>
              查询
            </Button>
            <Button onClick={onReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        rowKey="id"
        pagination={{
          current: page,
          pageSize: pageSize,
          total: total,
          showSizeChanger: true,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
          onShowSizeChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />
    </Card>
  );
};

export default AgentSubscription;
